import { type Ref, ref, computed, h, Fragment } from "vue";
import type { PlusColumn, FieldValues, OptionsRow } from "plus-pro-components";
import { ElUpload, ElButton } from "element-plus";
import { getToken, formatToken } from "@/utils/auth";
import { message } from "@/utils/message";
import { getSpots } from "@/api/zhaoyuan";
const { token } = getToken();
export function useForm(pageEnums: Ref<{ [key: string]: OptionsRow[] }>) {
  const formRules = {
    name: [
      {
        required: true,
        message: "请输入名称"
      }
    ]
  };
  const formColumns: PlusColumn[] = [
    {
      label: "名称",
      prop: "name"
    },

    {
      label: "地址",
      prop: "address"
    },
    {
      label: "描述",
      prop: "description",
      valueType: "textarea",
      fieldProps: {
        maxlength: 500,
        showWordLimit: true,
        autosize: { minRows: 2, maxRows: 10 }
      }
    },
    {
      label: "历程",
      prop: "experiences",
      valueType: "plus-input-tag"
    },
    {
      label: "图册",
      prop: "imageUrls",
      width: 100,
      renderField(value, onChange) {
        return h(Fragment, [
          h(
            ElUpload,
            {
              action: "api/api/document",
              multiple: true,
              limit: 9,
              headers: {
                Authorization: formatToken(token)
              },
              onSuccess: (response, file) => {
                // 确保 value 是数组
                const updatedValue = Array.isArray(value)
                  ? [...value, response.url]
                  : [response.url];
                onChange(updatedValue);
              },
              onError: (error, file) => {
                message("上传失败！", { type: "error" });
              }
            },
            () => h(ElButton, () => "点击上传")
          )
        ]);
      }
    }
  ];
  const formTitle = ref("");
  const formId = ref<number>(0);
  const formVisible = ref(false);
  const formValues = ref<FieldValues>({});
  const formOpen = async (title = "新增", row: any = {}) => {
    //重置表单
    if (title == "修改") {
      formId.value = row.id;
      const res = await getSpots(row.id);
      formValues.value = res;
    } else {
      formValues.value = {};
      formId.value = 0;
    }
    formTitle.value = title;
    formVisible.value = true;
  };

  return {
    formRules,
    formColumns,
    formVisible,
    formValues,
    formOpen,
    formTitle,
    formId
  };
}
